package com.project.util;

import lombok.SneakyThrows;

import java.io.*;

public class IoUtil {

    public static String readFile(File file) {
        StringBuilder stringBuilder = new StringBuilder();
        Reader reader = null;
        try {
            reader = new FileReader(file);
            char[] chars = new char[1024 * 4];
            int read = reader.read(chars);
            while (read != -1) {
                stringBuilder.append(chars, 0, read);
                read = reader.read(chars);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    public static void createPath(String path) {
        File file = new File(path);
        file.mkdirs();
    }

    @SneakyThrows
    public static void write(String javaTemplate, String path) {
        File file = new File(path);
        File parentFile = file.getParentFile();
        if ( !parentFile.exists() ) parentFile.mkdirs();
        if (file.exists()) file.delete();
        file.createNewFile();
        OutputStream writer = new FileOutputStream(file);
        writer.write(javaTemplate.getBytes());
        writer.flush();
        writer.close();
    }

    @SneakyThrows
    public static void fileReadWrite(File file, File target ){
        if ( target.exists() )target.delete();
        target.createNewFile();
        BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
        BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(target));
        byte[] bytes = new byte[1024*4];
        int read = reader.read(bytes);
        while ( read != -1 ){
            writer.write(bytes,0,read);
            read = reader.read(bytes);
        }
        writer.flush();
        reader.close();
        writer.close();
    }

    public static void fileTransfer(File file, String javaBasicPath) {
        if ( file.isFile() ){
            File target = new File(javaBasicPath);
            fileReadWrite(file, target);
        }else {
            File[] files = file.listFiles();
            for (File tf : files) {
                String tp = javaBasicPath+"\\"+tf.getName();
                File pf = new File(tp);
                pf.mkdirs();
                fileTransfer(tf, tp);
            }
        }
    }

}
